package top.ruanlitao.shortlink.admin.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import top.ruanlitao.shortlink.admin.common.convention.result.Result;
import top.ruanlitao.shortlink.admin.remote.ShortLinkActualRemoteService;
import top.ruanlitao.shortlink.admin.remote.dto.req.ShortLinkBatchCreateReqDTO;
import top.ruanlitao.shortlink.admin.remote.dto.req.ShortLinkCreateReqDTO;
import top.ruanlitao.shortlink.admin.remote.dto.req.ShortLinkPageReqDTO;
import top.ruanlitao.shortlink.admin.remote.dto.req.ShortLinkUpdateReqDTO;
import top.ruanlitao.shortlink.admin.remote.dto.resp.ShortLinkBaseInfoRespDTO;
import top.ruanlitao.shortlink.admin.remote.dto.resp.ShortLinkBatchCreateRespDTO;
import top.ruanlitao.shortlink.admin.remote.dto.resp.ShortLinkCreateRespDTO;
import top.ruanlitao.shortlink.admin.remote.dto.resp.ShortLinkPageRespDTO;
import top.ruanlitao.shortlink.admin.toolkit.EasyExcelWebUtil;

import java.util.List;

/**
 * 短链接后管控制层
 */
@RestController
@RequestMapping("/api/short-link/admin/v1")
@RequiredArgsConstructor
public class ShortLinkController {

    // 短链接中台远程调用服务（使用 SpringCloud OpenFeign）
    private final ShortLinkActualRemoteService shortLinkActualRemoteService;

    /**
     * 创建短链接
     */
    @PostMapping("/create")
    public Result<ShortLinkCreateRespDTO> createShortLink(@RequestBody ShortLinkCreateReqDTO requestParam) {
        return shortLinkActualRemoteService.createShortLink(requestParam);
    }

    /**
     * 按照分组 ID 分页查询短链接
     */
    @GetMapping("/page")
    public Result<Page<ShortLinkPageRespDTO>> pageShortLink(ShortLinkPageReqDTO requestParam) {
        return shortLinkActualRemoteService.pageShortLink(requestParam);
    }

    /**
     * 修改短链接
     */
    @PostMapping("/update")
    public Result<Void> updateShortLink(@RequestBody ShortLinkUpdateReqDTO requestParam) {
        return shortLinkActualRemoteService.updateShortLink(requestParam);
    }

    /**
     * 根据 URL 获取对应网站的标题
     */
    @GetMapping("/title")
    public Result<String> getTitleByUrl(@RequestParam("url") String url) {
        return shortLinkActualRemoteService.getTitleByUrl(url);
    }

    /**
     * 批量创建短链接
     */
    @PostMapping("/create/batch")
    public void batchCreateShortLink(@RequestBody ShortLinkBatchCreateReqDTO requestParam, HttpServletResponse response) {
        Result<ShortLinkBatchCreateRespDTO> result = shortLinkActualRemoteService.batchCreateShortLink(requestParam);
        if (result.isSuccess()) {
            // 将相应结果返回为一个Excel
            List<ShortLinkBaseInfoRespDTO> baseLinkInfos = result.getData().getBaseLinkInfos();
            EasyExcelWebUtil.write(response, "批量创建短链接-SaaS短链接系统", ShortLinkBaseInfoRespDTO.class, baseLinkInfos);
        }
    }
}
